#include <QFileDialog>
#include <QMessageBox>
#include <QTextStream>
#include <QDateTime>
#include "cclientpointmng.h"
#include "cglobal.h"

CClientPointMng::CClientPointMng(CClientData* pClient, QWidget *parent)
    : QWidget(parent), m_pClient(pClient)
{
	ui.setupUi(this);
    m_pModel = nullptr;
	m_nCurrentPage = 1;
	m_nPageSize = 100;
	m_nTotalPages = 0;
    m_sFilterText = "*";//默认筛选全部
    m_vecFilterTags.clear();
	initConnect();
	initUi();
    setFilter(ui.lineEditFilter->text());
	updateButtonStates();
	loadPointList();
}

CClientPointMng::~CClientPointMng()
{}

void CClientPointMng::initConnect()
{
	connect(ui.pushButtonJump, &QPushButton::clicked, this, &CClientPointMng::slotPushButtonJump);
	connect(ui.pushButtonNext, &QPushButton::clicked, this, &CClientPointMng::slotPushButtonNext);
	connect(ui.pushButtonPre, &QPushButton::clicked, this, &CClientPointMng::slotPushButtonPre);
    connect(ui.comboBoxPageSize, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(slotComboBoxPageSizeChanged(const QString&)));
	connect(ui.pushButtonExport, &QPushButton::clicked, this, &CClientPointMng::slotPushButtonExport);
    connect(ui.pushButtonFilter, &QPushButton::clicked, this, &CClientPointMng::slotPushButtonFilter);
}

void CClientPointMng::initUi()
{
	ui.comboBoxPageSize->addItems({ "100","200","500" });
	m_pModel = new QStandardItemModel();
	QStringList headerListAction;		//水平表头
	headerListAction << A2T("索引") << A2T("测点名") << A2T("测点描述") << A2T("扫描频率(ms)") << A2T("读取权限") << A2T("数据类型") <<
		A2T("采集驱动类型") << A2T("采集驱动地址") << A2T("keyAddr") << A2T("死区") << A2T("例外报告");
	QList<quint16> listColumnWidth;		//列宽
    listColumnWidth << 50 << 100 << 350 << 110 << 100 << 100 << 150 << 200 << 100 << 100 << 100;
	QList<quint16> listColumnHidden;	//隐藏列
	//设置列数
	m_pModel->setColumnCount(headerListAction.count());
	//设置表头
	m_pModel->setHorizontalHeaderLabels(headerListAction);
	ui.tableView->setModel(m_pModel);
	//设置列宽
	for (int i = 0; i < listColumnWidth.count(); i++)
	{
		ui.tableView->setColumnWidth(i, listColumnWidth.at(i));
	}
	//隐藏列
	if (0 < listColumnHidden.count())
	{
		for (quint16 i = 0; i < listColumnHidden.count(); i++)
		{
			ui.tableView->hideColumn(listColumnHidden.at(i));
		}
	}

    ui.pushButtonExport->hide();
}

void CClientPointMng::loadPointList()
{
    if(m_pModel==nullptr)
        return;
	//首先清空列表
	m_pModel->removeRows(0, m_pModel->rowCount());
    //刷新状态
	const int nStart = (m_nCurrentPage - 1) * m_nPageSize;
    const int nEnd = qMin(nStart + m_nPageSize, m_vecFilterTags.size());
	for (int i = nStart; i < nEnd; ++i)
	{
        CTagData* pTag = m_vecFilterTags[i];
		QList<QStandardItem*> rowItems;
		rowItems << new QStandardItem(QString::number(pTag->m_nIndex));
		rowItems << new QStandardItem(pTag->m_sTagName);
		rowItems << new QStandardItem(pTag->m_sTagDesc);
		rowItems << new QStandardItem(QString::number(pTag->m_nScanRate));
		rowItems << new QStandardItem(pTag->m_sDataAccess);
		switch (pTag->m_nDataType)
		{
		case CTagData::enUint8:
			rowItems << new QStandardItem(A2T("Uint8"));
			break;
		case CTagData::enInt16:
			rowItems << new QStandardItem(A2T("Int16"));
			break;
		case CTagData::enUint16:
			rowItems << new QStandardItem(A2T("Uint16"));
			break;
		case CTagData::enInt32:
			rowItems << new QStandardItem(A2T("Int32"));
			break;
		case CTagData::enUint32:
			rowItems << new QStandardItem(A2T("Uint32"));
			break;
		case CTagData::enInt64:
			rowItems << new QStandardItem(A2T("Int64"));
			break;
		case CTagData::enUint64:
			rowItems << new QStandardItem(A2T("Uint64"));
			break;
		case CTagData::enFloat:
			rowItems << new QStandardItem(A2T("Float"));
			break;
		case CTagData::enDouble:
			rowItems << new QStandardItem(A2T("Double"));
			break;
		case CTagData::enString:
			rowItems << new QStandardItem(A2T("String"));
			break;
		default:
			rowItems << new QStandardItem(A2T(""));
			break;
		}
		rowItems << new QStandardItem(pTag->m_sCollectDrv);
		rowItems << new QStandardItem(pTag->m_sCollectAddr);
		rowItems << new QStandardItem(pTag->m_sKeyAddr);
        rowItems << new QStandardItem(QString::number(pTag->m_dDeadband));
        rowItems << new QStandardItem(pTag->m_nExceptionReport==0 ? A2T("否"):A2T("是"));
        for(auto item:rowItems)
        {
            item->setTextAlignment(Qt::AlignCenter);
        }
		m_pModel->appendRow(rowItems);
	}
	updatePageInfo();
}

void CClientPointMng::updatePageInfo()
{
    m_nTotalPages = (m_vecFilterTags.size() + m_nPageSize - 1) / m_nPageSize;
	m_nTotalPages = qMax(m_nTotalPages, 0); // 处理空数据情况
	ui.labelPage->setText(QString(A2T("第 %1 页 / 共 %2 页").arg(m_nCurrentPage).arg(m_nTotalPages)));
	updateButtonStates(); // 每次更新页面时同步按钮状态
}

void CClientPointMng::updateButtonStates()
{
	const bool hasPrev = m_nCurrentPage > 1;
	const bool hasNext = m_nCurrentPage < m_nTotalPages;

	ui.pushButtonPre->setEnabled(hasPrev);
    ui.pushButtonNext->setEnabled(hasNext);
}

void CClientPointMng::setFilter(const QString &sFilterText)
{
    QMutexLocker(m_pClient->m_pMutex);
    m_vecFilterTags.clear();
    // 遍历所有标签进行筛选
    for (CTagData* pTag : m_pClient->m_vecTag)
    {
        if (sFilterText.isEmpty()|| sFilterText=="*" || pTag->m_sTagName.contains(sFilterText, Qt::CaseInsensitive))
        {
            m_vecFilterTags.append(pTag);
        }
    }
    // 重置分页到第一页
    m_nCurrentPage = 1;

    // 计算总页数
    m_nTotalPages = qMax(1, (m_vecFilterTags.size() + m_nPageSize - 1) / m_nPageSize);
}

void CClientPointMng::slotComboBoxPageSizeChanged(const QString& sSize)
{
	m_nPageSize = sSize.toInt();
	m_nCurrentPage = 1; // 重置到第一页
	loadPointList();
}

void CClientPointMng::slotPushButtonPre()
{
	if (m_nCurrentPage > 1)
	{
		m_nCurrentPage--;
		loadPointList();
	}
}

void CClientPointMng::slotPushButtonNext()
{
	const int nTotalPages = (m_pClient->m_vecTag.size() + m_nPageSize - 1) / m_nPageSize;
	if (m_nCurrentPage < nTotalPages) 
	{
		m_nCurrentPage++;
		loadPointList();
	}
}

void CClientPointMng::slotPushButtonJump()
{
	bool ok;
	int page = ui.lineEditPage->text().toInt(&ok);
	if (!ok || page < 1 || page >(m_pClient->m_vecTag.size() + m_nPageSize - 1) / m_nPageSize)
	{
		QMessageBox::warning(this, A2T("错误"), A2T("请输入有效页码"));
		return;
	}

	m_nCurrentPage = page;
    loadPointList();
}

void CClientPointMng::slotPushButtonFilter()
{
    setFilter(ui.lineEditFilter->text().trimmed());
    loadPointList();
}

void CClientPointMng::slotPushButtonExport()
{
	QString sFilePath= QCoreApplication::applicationDirPath() + "/TagCfg/"+m_pClient->m_sName+"/"+ m_pClient->m_sName+".csv";
	QString sContentEx = QString("#gwtagfile,V1.0.2025.0423,")+QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss");
	QString sTitile = "#index,name,desc,scanRate,dataAccess,dataType,dataCollectDrv,dataCollectDrvAddr,keyAddr,deadband,exceptionReport";

	// 获取目录路径
	QString dirPath = QFileInfo(sFilePath).absolutePath();

	// 如果目录不存在，则创建它
	QDir dir;
	if (!dir.exists(dirPath))
	{
		if (!dir.mkpath(dirPath)) 
		{
			QMessageBox::warning(nullptr, A2T("错误"), A2T("无法创建目录."));
			return;
		}
	}
	// 打开文件以写入
	QFile file(sFilePath);
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
	{
		QMessageBox::warning(nullptr, A2T("错误"), A2T("无法打开文件以写入."));
		return;
	}

	QTextStream out(&file);

	//写入附加内容
	out << sContentEx << "\n";
	out << sTitile << "\n";

	m_pClient->m_pMutex->lock();
	for (int i = 0; i < m_pClient->m_vecTag.size();i++)
	{
		CTagData* pTag = m_pClient->m_vecTag[i];
		out << pTag->m_nIndex;
		out << ",";
		out << pTag->m_sTagName;
		out << ",";
		out << pTag->m_sTagDesc;
		out << ",";
		out << pTag->m_nScanRate;
		out << ",";
		out << pTag->m_sDataAccess;
		out << ",";
		out << pTag->m_nDataType;
		out << ",";
		out << pTag->m_sCollectDrv;
		out << ",";
		out << pTag->m_sCollectAddr;
		out << ",";
		out << pTag->m_sKeyAddr;
		out << ",";
		out << pTag->m_dDeadband;
		out << ",";
		out << pTag->m_nExceptionReport;
		out << "\n";
	}
	m_pClient->m_pMutex->unlock();
	file.close(); // 关闭文件
	QMessageBox::information(nullptr, A2T("成功"), A2T("表格数据已成功导出到") + sFilePath);
}
